package com.yanze.controller;

import com.yanze.utils.BaseJSONResult;
import com.yanze.utils.C;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("file")
public class FileController {
    /**
     * 单个文件上传具体实现方法;
     *
     * @param file
     * @return
     */
    @RequestMapping(path = "/upload", method = RequestMethod.POST)
    public BaseJSONResult handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (!file.isEmpty()) {
            String originalFilename = file.getOriginalFilename();
            String friendPath = C.path.IMG_FRIEND + UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
            String targetPath = C.path.IMG_PATH + friendPath;
            try {
                File targetfile = new File(targetPath);
                if (!targetfile.exists()) {
                    targetfile.createNewFile();
                }
                file.transferTo(targetfile);//保存图片至指定路径
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return BaseJSONResult.errorMsg("上传失败," + e.getMessage());
            } catch (IOException e) {
                e.printStackTrace();
                return BaseJSONResult.errorMsg("上传失败," + e.getMessage());
            }
            //保存成功，更新数据库中User图片路径
            return BaseJSONResult.ok(friendPath);
        } else {
            return BaseJSONResult.errorMsg("上传失败，因为文件是空的.");
        }
    }
}
